package mvc.core.log;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

/**
 * 自定义日志工具
 * 
 * @author liuzy
 * @version 2015年5月16日
 */
public class Logger {
	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	private String clazzName;
	
	protected static Level level = Level.INFO;
	
	private Logger(String clazzName) {
		this.clazzName = clazzName;
	}
	
	public static Logger getLogger(Class<?> clazz) {
		return new Logger(clazz.getName());
	}

	static {
		InputStream in = null;
		try {
			in = Logger.class.getClassLoader().getResourceAsStream("log.properties");
			Properties p = new Properties();
			p.load(in);
			String lvl = p.getProperty("log.level").toUpperCase();
			switch (lvl) {
			case "DEBUG":
				Logger.level = Level.DEBUG;
				break;
			case "INFO":
				Logger.level = Level.INFO;
				break;
			case "WARN":
				Logger.level = Level.WARN;
				break;
			case "ERROR":
				Logger.level = Level.ERROR;
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
		}
	}
	
	public void debug(String message) {
		if (level == Level.DEBUG)
			this.log("DEBUG", message);
	}
	
	public void debug(String message,  Throwable t) {
		if (level == Level.DEBUG)
			this.log("DEBUG", message, t);
	}
	
	public void info(String message) {
		if (level == Level.DEBUG || level == Level.INFO)
			this.log("INFO", message);
	}
	
	public void info(String message, Throwable t) {
		if (level == Level.DEBUG || level == Level.INFO)
			this.log("INFO", message, t);
	}
	
	public void warn(String message) {
		if (level == Level.DEBUG || level == Level.INFO || level == Level.WARN)
			this.log("WARN", message);
	}
	
	public void warn(String message, Throwable t) {
		if (level == Level.DEBUG || level == Level.INFO || level == Level.WARN)
			this.log("WARN", message, t);
	}
	
	public void error(String message) {
		this.log("ERROR", message);
	}
	
	public void error(String message, Throwable t) {
		this.log("ERROR", message, t);
	}
	
	private void log(String level, String message) {
		StackTraceElement ste = Thread.currentThread().getStackTrace()[3];
		StringBuilder sb = new StringBuilder();
		sb.append("[").append(level).append("] ").append(sdf.format(new Date()));
		sb.append(" [").append(clazzName).append(".").append(ste.getMethodName());
		sb.append("(").append(ste.getFileName()).append(":");
		sb.append(ste.getLineNumber()).append(")] ").append(message);
		System.out.println(sb.toString());
	}
	
	private void log(String level, String message, Throwable t) {
		this.log(level, message);
		t.printStackTrace();
	}
}



